
#ifndef __RSP_OBJREF__HEADER_FILE__
#define __RSP_OBJREF__HEADER_FILE__

#include "rsp_def.h"
#include "tile.h"

////////////////////////////////////////////////////////////////////////////////
template <class T, bool OWNING>
class rsp_dynarray : public dynarray<T*>
{
public:

    rsp_dynarray()
    {
    }

    explicit rsp_dynarray( uint n )
    {
        this->need_newc(n);
    }

    ~rsp_dynarray()
    {
    }


    typedef binstream_dereferencing_containerTC<T,dynarray<T*>::binstream_container>  container;

    container get_container()
    {
        container bc( dynarray<T*>::binstream_container( *this, this->size(), 0, 0 ) );
        return bc;
    }


    void init( uint n )
    {
        DASSERT( OWNING );
        uint ts = this->size();

        this->needc(n);
        for( uint i=ts; i<n; ++i )
            this->_ptr[i] = (T*) new typename type_select<OWNING,T,int>::type;// T;
    }

    /// Copy constructor
    /**
        This is executed only on the client
    **/
    rsp_dynarray& operator = (const rsp_dynarray& src)
    {
#ifdef _RSP_SERVER_SIDE
        DASSERT(0); //shouldn't ever get called on the server side
#else
        DASSERT( src.size() == 0  ||  rsp_controller::current->client_side() );

        //map pointers to ref objects to pointers to bound objects
        this->needc( src.size() );

        for( uint i=0; i<this->size(); ++i )
        {
            if(!OWNING)
                this->_ptr[i] = 0;

            if( src[i] == 0 )  continue;

            //rsp_base* os = rsp_base::from_oid( src[i] );

            this->_ptr[i] = (T*) src[i]->create_bound_object();
        }
#endif //_RSP_SERVER_SIDE

        return *this;
    }



    ///Full object state save
    void state_save( frame_command_buffer& fcb ) const
    {
        uint n = this->size();
        fcb << (ushort)n;

        for( uint i=0; i<n; ++i )
            fcb << (ushort)this->_ptr[i]->get_slot();
    }

    void state_load( frame_command_reader& fcr, rsp_tile* tile )
    {
        DASSERT( rsp_controller::current->client_side() );
        //DASSERT( _flags != INTERPOLATED );

        ushort n;
        fcr >> n;

        this->needc(n);

        for( uint i=0; i<n; ++i )
        {
            ushort slot;
            fcr >> slot;

            //rsp_base* os = rsp_base::from_oid(o);
            rsp_base* os = tile->get_object_from_slot(slot);
            DASSERT(os);

            this->_ptr[i] = (T*)os;
        }

        //_flags = REFERENCE;
    }

};


#endif //__RSP_OBJREF__HEADER_FILE__
